package com.hx.er.action.admin.food;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.beans.factory.annotation.Autowired;

import com.hx.er.action.base.ErAdminAction;
import com.hx.er.bean.detail.FoodTemplateDetailBean;
import com.hx.er.common.exception.ErException;
import com.hx.er.common.system.Constants;
import com.hx.er.common.system.ErLanguages;
import com.hx.er.common.system.ErProperties;
import com.hx.er.common.util.FileUtil;
import com.hx.er.common.util.StringUtil;
import com.hx.er.service.admin.IAdminFoodService;

public class AdminFoodTemplateEditAction extends ErAdminAction {

	// 序列化ID
	private static final long serialVersionUID = 5351398597395998441L;

	// 页面国际化
	public static final String FOOD_PICTURE_EMPTY_MSG = "admin.foodList.message.edit.empty.foodPicture";
	public static final String FOOD_NAME_EMPTY_MSG = "admin.foodList.message.edit.empty.foodName";
	public static final String FOOD_PRICE_EMPTY_MSG = "admin.foodList.message.edit.empty.price";
	public static final String FOOD_PRICE_NUMBER_MSG = "admin.foodList.message.edit.number.price";
	public static final String PICTURE_PATH_EMPTY_MSG = "admin.foodList.message.edit.empty.picturePath";

	// 菜品ID
	private long foodTemplateId;
	// 价格
	private String priceStr;
	// 获取上传文件
	private File foodPicture;
	// 获取上传文件名称
	private String foodPictureFileName;
	// 获取上传文件类型
	private String foodPictureContentType;
	// 菜品实例
	private FoodTemplateDetailBean foodTemplateDetailBean;
	// 多语言标签名
	private String labelLang1;
	private String labelLang2;
	private String labelLang3;
	private String labelLang4;
	private String labelLang5;

	@Autowired
	private IAdminFoodService adminFoodService;

	public String init() throws IOException {
		// 初始化页面
		this.initPage();

		return SUCCESS;
	}

	public String upload() {
		try {
			if (!this.checkUploadParams()) {
				return INPUT;
			}

			// 循环上传的文件
			InputStream is = null;
			OutputStream os = null;

			try {
				is = new FileInputStream(this.foodPicture);

				// 得到图片保存的位置(根据root来得到图片保存的路径在tomcat下的该工程里)
				String root = request.getServletContext().getRealPath("/");
				this.foodTemplateDetailBean.setPicturePath(ErProperties.getProperty(Constants.PROPERTY_PICTURE_ROOT_PATH) + "\\" + this.getNewFileName());
				File destFile = new File(root, this.foodTemplateDetailBean.getPicturePath());
				FileUtil.createDir(destFile);

				// 把图片写入到上面设置的路径里
				os = new FileOutputStream(destFile);
				byte[] buffer = new byte[400];
				int length = 0;
				while ((length = is.read(buffer)) > 0) {
					os.write(buffer, 0, length);
				}
			} catch (FileNotFoundException e) {
				throw new ErException(e);
			} catch (IOException e) {
				throw new ErException(e);
			} finally {
				try {
					if (is != null) {
						is.close();
					}
					if (os != null) {
						os.close();
					}
				} catch (IOException e) {
					throw new ErException(e);
				}
			}
		} catch (ErException e) {
			this.addActionError(super.getText(OPERATION_FAILURE_MSG));
			return INPUT;
		}

		// 语言初始化
		this.initLang();

		return UPLOAD;
	}

	/**
	 * 保存新菜品
	 * 
	 * @return
	 * @throws IOException
	 */
	public String save() throws IOException {
		try {
			// 属性校验
			if (!this.checkSaveParams()) {
				// 添加错误信息
				this.addActionError(super.getText(EDIT_FAILURE_MSG));
				// 初始化页面
				this.initPage();
				return INPUT;
			}

			// 读取图片文件
			String root = request.getServletContext().getRealPath("/");
			File pictureFile = new File(root, this.foodTemplateDetailBean.getPicturePath());

			// 循环上传的文件
			InputStream is = new FileInputStream(pictureFile);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
			byte[] tempByteArray = new byte[1024];
			while (is.read(tempByteArray) != -1) {
				bos.write(tempByteArray);
			}

			this.foodTemplateDetailBean.setPictureFile(bos.toByteArray());
			if (is != null) {
				is.close();
			}

			// 设置食品属性
			this.foodTemplateDetailBean.setUpdateUserId(super.userInfoLogin.getUserId());
			this.foodTemplateDetailBean.setPrice(Double.parseDouble(this.priceStr));
			this.foodTemplateDetailBean.setFoodTemplateId(this.foodTemplateId);

			// 插入数据库
			int count = this.adminFoodService.updateFoodTemplate(this.foodTemplateDetailBean);
			if (count == 0) {
				// 添加错误信息
				this.addActionError(super.getText(EDIT_FAILURE_MSG));
				// 初始化页面
				this.initPage();
				return INPUT;
			} else {
				// 添加成功信息
				this.addActionMessage(super.getText(EDIT_SUCCESS_MSG));
				return SAVE;
			}
		} catch (IOException e) {
			// 错误信息
			this.addActionError(super.getText(EDIT_FAILURE_MSG));
			// 初始化页面
			this.initPage();
			e.printStackTrace();
			return INPUT;
		}
	}

	/**
	 * 检查文件，如果不存在则重新生成
	 * 
	 * @throws ErException
	 * @throws IOException
	 */
	private void checkPictureFile() throws IOException {
		// 如果食品对象不存在，则略过该方法
		if (this.foodTemplateDetailBean == null) {
			return;
		}

		// 声明输出流
		OutputStream fos = null;

		// 循环处理列表中所有对象
		String root = request.getServletContext().getRealPath("/");
		File pictureFile = new File(root, this.foodTemplateDetailBean.getPicturePath());

		// 如果所在目录不存在，则先创建
		FileUtil.createDir(pictureFile);

		// 如果文件不存在，则写文件
		if (!pictureFile.exists()) {
			fos = new FileOutputStream(pictureFile);
			fos.write(this.foodTemplateDetailBean.getPictureFile());
			if (fos != null) {
				fos.close();
			}
		}
	}

	/**
	 * 获取图片的新名称
	 * 
	 * @return
	 */
	private String getNewFileName() {
		String suffix = this.foodPictureFileName.substring(this.foodPictureFileName.lastIndexOf('.'));
		long time = System.currentTimeMillis();

		return String.valueOf(Constants.PROPERTY_SUPER_ADMIN_PICTURE_PATH) + "\\" + time + suffix;
	}

	/**
	 * 上传图片时检查参数
	 * 
	 * @return
	 */
	private boolean checkUploadParams() {
		// 图片验证
		if (this.foodPicture == null) {
			this.addFieldError("msg.restName", super.getText(FOOD_PICTURE_EMPTY_MSG));
		}

		// 错误信息数量
		int errCount = this.getActionErrors().size() + this.getFieldErrors().size();

		return errCount == 0;
	}

	/**
	 * 保存食品信息时检查参数
	 * 
	 * @return
	 * @throws IOException 
	 */
	private boolean checkSaveParams() {
		// 菜名校验
		if (StringUtil.isEmpty(this.foodTemplateDetailBean.getFoodName1())) {
			this.addFieldError("msg.foodName", super.getText(FOOD_NAME_EMPTY_MSG));
		}

		// 图片验证，只要文件插件里有，就上传，不管原来的路径是什么。此处与菜品添加的做法不同。
		// 原因是：菜品添加的时候，要先判断是否已经点过“上传”按钮，如果没点过，就直接从file中获取图片进行上传，如果点过，则只需要把已经上传到服务器的图片上传就可以了。
		// 而更新时原来的图片本身就存在了，如果点了上传，只不过是更新了一下图片而已。所以只需要判断是否新上传的文件，而不必担心未上传文件，即便未上传，那么也是保存原有图片即可。
		if (!StringUtil.isEmpty(this.foodPictureFileName)) {
			// 如果文件空间已经加载了文件名，只是文件没有预览上传，则直接上传。
			this.upload();
		}

		// 价格校验
		if (StringUtil.isEmpty(StringUtil.trim(this.priceStr))) {
			this.addFieldError("msg.price", super.getText(FOOD_PRICE_EMPTY_MSG));
		} else if (!StringUtil.isNumeric(StringUtil.trim(this.priceStr))) {
			this.addFieldError("msg.price", super.getText(FOOD_PRICE_NUMBER_MSG));
		}

		// 错误信息数量
		int errCount = this.getActionErrors().size() + this.getFieldErrors().size();

		return errCount == 0;
	}

	private void initPage() throws IOException {
		// 查询食品详细信息
		this.foodTemplateDetailBean = this.adminFoodService.getFoodTemplateAliveById(this.foodTemplateId);
		this.priceStr = this.foodTemplateDetailBean.getPrice().toString();

		// 语言
		this.initLang();

		// 检查图片
		this.checkPictureFile();
	}

	private void initLang() {
		// 语言
		if (ErLanguages.getLangList().size() > 0) {
			this.labelLang1 = ErLanguages.getLocale(ErLanguages.getLangList().get(0).getLangId()).getLanguage().toUpperCase();
		}
		if (ErLanguages.getLangList().size() > 1) {
			this.labelLang2 = ErLanguages.getLocale(ErLanguages.getLangList().get(1).getLangId()).getLanguage().toUpperCase();
		}
		if (ErLanguages.getLangList().size() > 2) {
			this.labelLang3 = ErLanguages.getLocale(ErLanguages.getLangList().get(2).getLangId()).getLanguage().toUpperCase();
		}
		if (ErLanguages.getLangList().size() > 3) {
			this.labelLang4 = ErLanguages.getLocale(ErLanguages.getLangList().get(3).getLangId()).getLanguage().toUpperCase();
		}
		if (ErLanguages.getLangList().size() > 4) {
			this.labelLang5 = ErLanguages.getLocale(ErLanguages.getLangList().get(4).getLangId()).getLanguage().toUpperCase();
		}
	}

	public long getFoodTemplateId() {
		return foodTemplateId;
	}

	public void setFoodTemplateId(long foodTemplateId) {
		this.foodTemplateId = foodTemplateId;
	}

	public FoodTemplateDetailBean getFoodTemplateDetailBean() {
		return foodTemplateDetailBean;
	}

	public void setFoodTemplateDetailBean(FoodTemplateDetailBean foodTemplateDetailBean) {
		this.foodTemplateDetailBean = foodTemplateDetailBean;
	}

	public String getPriceStr() {
		return priceStr;
	}

	public void setPriceStr(String priceStr) {
		this.priceStr = priceStr;
	}

	public File getFoodPicture() {
		return foodPicture;
	}

	public void setFoodPicture(File foodPicture) {
		this.foodPicture = foodPicture;
	}

	public String getFoodPictureFileName() {
		return foodPictureFileName;
	}

	public void setFoodPictureFileName(String foodPictureFileName) {
		this.foodPictureFileName = foodPictureFileName;
	}

	public String getFoodPictureContentType() {
		return foodPictureContentType;
	}

	public void setFoodPictureContentType(String foodPictureContentType) {
		this.foodPictureContentType = foodPictureContentType;
	}

	public String getLabelLang1() {
		return labelLang1;
	}

	public void setLabelLang1(String labelLang1) {
		this.labelLang1 = labelLang1;
	}

	public String getLabelLang2() {
		return labelLang2;
	}

	public void setLabelLang2(String labelLang2) {
		this.labelLang2 = labelLang2;
	}

	public String getLabelLang3() {
		return labelLang3;
	}

	public void setLabelLang3(String labelLang3) {
		this.labelLang3 = labelLang3;
	}

	public String getLabelLang4() {
		return labelLang4;
	}

	public void setLabelLang4(String labelLang4) {
		this.labelLang4 = labelLang4;
	}

	public String getLabelLang5() {
		return labelLang5;
	}

	public void setLabelLang5(String labelLang5) {
		this.labelLang5 = labelLang5;
	}

}
